package _10个棘手的面试题;

/**
 * Created by Administrator on 2017/9/3.
 */
public class _5_float_accuracy {
    public static void main(String[] args) {
        System.out.println(0.1);
        System.out.println(0.1 * 3);
        System.out.println(0.1 * 3 - 0.3);

        //模拟计算机内部浮点数的表示
        double sum = 0;
        double temp = 1.0 / 8; //初始值1.0/8是大于0.1的最小二进制表示数, 即2^(-3)
        for (int j = 0; sum < 0.1; j++) {
            temp = temp / 2;
            System.out.println("第" + j + "个加数：" + temp);
            sum += temp;
            if (sum > 0.1) sum -= temp;  //只能使和越来越接近1.0,但是绝对不能超过
            System.out.println("实时的sum值：" + sum);
        }
        //最终sum虽然输出1.0,但是那只是计算机的精度限制
        System.out.println(sum - 0.1);  //0.0
        System.out.println(sum * 3 - 0.3); //5.551115123125783E-17
    }
}

